const app = getApp()
const cookieUtil = require("../../utils/cookie.js")
Page({
	data: {
		inputLists: [
			{
				name: "phoneNumber",
				inputText: "电话号码",
				maxLength: 11,
				type: "number"
			}
		],
		registerHeaderDict: {
			logoSrc: "/static/logo.png",
			title: "Campus map",
			desc: "Join in Campus map Community"
		},
		buttonText: "登录/注册"
	},
	onSubmit(e) {
		//拉起加载
		my.showLoading({
			content: '加载中...',
			delay: 300,
		})
		//提交到服务器的地址
		const url = app.globalData.baseUrl + app.globalData.registerUrl
		//将用户登录状态写入缓存中

		// 由于没有登录页面，所以点击后就写到缓存中，不清除，值任意
		// my.setStorage({
		//   key: 'userStatus',
		//   data: 'userLogin',
		// })

		const {
			phoneNumber,
		} = e.detail.value

		let promise = new Promise((resolve, reject) => {
			my.request({
				url,
				data: {
					phoneNumber,
				},
				headers: {
					'content-type': 'application/x-www-form-urlencoded'
				},
				method: "POST",
				success: (res) => {
					resolve(res)
				}
			})
		})

		promise.then((res) => {
			console.log(res)
			my.hideLoading()
			if (res.data.status == "fail") {			
				my.showToast({
					type: 'fail',
					content: res.data.message,
					duration: 2000,
				})
			} else {
				//保存cookie
				console.log(res)
				const cookie = cookieUtil.getSessionIdFromResponse(res)
				console.log(cookie)
				cookieUtil.setCookieToStorage(cookie)
				
				//保存用户名
				//app.globalData.userInfo.name = studentName
				my.showToast({
					type: 'success',
					content: res.data.message,
					duration: 2000,
					success: () => {
						app.globalData.userStatus = true
						if(content == "注册成功") {
							my.switchTab({
								url: '/pages/registerfirst/registerfirst?phoneNumber=' + phoneNumber
							})
						}
						if(content == "登录成功") {
							//读取studentName,classInfo,gender,avatar,nickName
							my.switchTab({
								url: '/pages/my_new/my_new'
							})
						}
					}
				})
			}
		})
	},

	onLoad() {},
});
